package com.tongji.housediy.utils
{
	import com.tongji.housediy.view.components.AbstractDrawingRoom;
	import com.tongji.housediy.view.components.AbstractRulerField;
	import com.tongji.housediy.view.components.Furniture;
	import com.tongji.housediy.view.components.GridContainer;
	import com.tongji.housediy.view.components.IndependentFloor;
	import com.tongji.housediy.view.components.InteriorWall;
	import com.tongji.housediy.view.components.RoomBorder;
	import com.tongji.housediy.view.components.RoomFloor;
	import com.tongji.housediy.view.components.RoomShape;
	import com.tongji.housediy.view.components.RotationBtn;
	
	import de.polygonal.ds.DListNode;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import mx.controls.Image;
	import mx.core.UIComponent;

	/**
	 * 
	 * @author chenchao
	 * 
	 */
	public class CollisionDetection
	{
		public static function isCollisionWithOther(roomChild:UIComponent):Boolean
		{
			/*if (isCollisionWithBorder(roomChild))
				return true;*/
			
			if (roomChild is Furniture || roomChild is InteriorWall )
			{
				var roomFloor:RoomFloor = roomChild.parent as RoomFloor;
				
				for (var i:int = 0; i < roomFloor.numChildren; i++)
				{
					var floorChild:DisplayObject = roomFloor.getChildAt(i) as DisplayObject;
					if (roomChild != floorChild && !(floorChild is IndependentFloor))
					{
						if (complexHitTestObject(roomChild, floorChild))
							return true;
					}
				}
			}
			if (roomChild.parent is InteriorWall )
			{
				var roomFloor2:RoomFloor = roomChild.parent.parent as RoomFloor;
				
				for (var i1:int = 0; i1 < roomFloor.numChildren; i1++)
				{
					var floorChild1:DisplayObject = roomFloor.getChildAt(i1) as DisplayObject;
					if (roomChild.parent != floorChild && !(floorChild is IndependentFloor))
					{
						if (complexHitTestObject(roomChild, floorChild))
							return true;
					}
				}
			}
			return false;
		}
		
		public static function isCollisionWithInteriorWall(hostObj:UIComponent):Boolean
		{
			if (hostObj.parent.parent.parent is AbstractDrawingRoom)
			{
				var room:AbstractDrawingRoom = hostObj.parent.parent.parent as AbstractDrawingRoom;
				
				var currentNode:DListNode = room.borderVertexList.head;
				while (currentNode.next != room.borderVertexList.head)
				{
					currentNode = currentNode.next;
					if (currentNode.data is RoomBorder)
					{
						if (complexHitTestObject(hostObj.parent, (currentNode.data as RoomBorder).drawShape))
							return true;
					}
				}
			}
			
			return false;
		}
		public static function isCollisionWithBorder(hostObj:UIComponent):Boolean
		{
			if (hostObj.parent.parent is AbstractDrawingRoom)
			{
				var room:AbstractDrawingRoom = hostObj.parent.parent as AbstractDrawingRoom;
				
				var currentNode:DListNode = room.borderVertexList.head;
				while (currentNode.next != room.borderVertexList.head)
				{
					currentNode = currentNode.next;
					if (currentNode.data is RoomBorder)
					{
						if (complexHitTestObject(hostObj, (currentNode.data as RoomBorder).drawShape))
							return true;
					}
				}
			}
			
			return false;
		}
		
		public static function isCollision(roomShape:RoomShape):Boolean
		{
			var gridContainer:GridContainer = (roomShape.parent as AbstractDrawingRoom).parentGridContainer;
			
			for (var i:int = 0; i < gridContainer.numChildren; i++)
			{
				if (gridContainer.getChildAt(i) != (roomShape.parent as AbstractDrawingRoom)
					&& (gridContainer.getChildAt(i) is AbstractDrawingRoom)
					&& !(gridContainer.getChildAt(i) is IndependentFloor))
				{
					var currentRoom:AbstractDrawingRoom = gridContainer.getChildAt(i) as AbstractDrawingRoom;
					if (complexHitTestObject((roomShape.parent as AbstractDrawingRoom).roomFloor, currentRoom.roomFloor))
					{
						return true;
					}
				}
			}
			
			// 如果拖拽的顶点或者边框，则还需要比较它们同 RoomFloor 内部孩子之间的碰撞
			if (!(roomShape is RoomFloor))
			{
				var parentRoom:AbstractDrawingRoom = roomShape.parent as AbstractDrawingRoom;
				var childLength:int = parentRoom.roomFloor.numChildren;
				
				for (var j:int = 0; j < childLength; j++)
				{
					var floorChild:DisplayObject = parentRoom.roomFloor.getChildAt(j) as DisplayObject;
					if (!(floorChild is Image))
					{
						if (isCollisionWithBorder(floorChild as UIComponent))
							return true;
					}
				}
			}
			
			return false;
		}
		
		///////////////////////////////////////////////by zazisb  返回碰撞物体的Array
		public static function relatedCollisionObject(testRoom:AbstractDrawingRoom):Array
		{
			var relatedCollisionObject:Array = new Array();
			var gridContainer:GridContainer = testRoom.parentGridContainer;
			
			for (var i:int = 0; i < gridContainer.numChildren; i++)
			{
				if (gridContainer.getChildAt(i) != testRoom
					&& (gridContainer.getChildAt(i) is AbstractDrawingRoom)
					&& !(gridContainer.getChildAt(i) is IndependentFloor))
				{
					var currentRoom:AbstractDrawingRoom = gridContainer.getChildAt(i) as AbstractDrawingRoom;
					if (complexHitTestObject(testRoom, currentRoom))
					{
						relatedCollisionObject.push(currentRoom);
					}
				}
			}
			return relatedCollisionObject;
		}
		///////////////////////////////////////////
		
		//添加扩张墙后判断房间是否碰撞
		public static function isExpandRoomCollision(newRoom:AbstractDrawingRoom):Boolean
		{
			var gridContainer:GridContainer = newRoom.parentGridContainer;
			
			for(var i:int = 0; i < gridContainer.numChildren; i++)
			{
				if(gridContainer.getChildAt(i) != newRoom
					&& (gridContainer.getChildAt(i) is AbstractDrawingRoom))
					{
						var currentRoom:AbstractDrawingRoom = gridContainer.getChildAt(i) as AbstractDrawingRoom;
						if(complexHitTestObject(newRoom, currentRoom))
						{
							return true;
						}
					}
			}
			return false;
		}
		/**
		 * 判断两个物体是否碰撞
		 * @param target1 待检测碰撞物体1
		 * @param target2 待检测碰撞物体2
		 * @param accurracy
		 * @return 是否碰撞
		 * 
		 */		
		public static function complexHitTestObject(target1:DisplayObject, target2:DisplayObject, accurracy:Number = 1):Boolean
		{
			return complexIntersectionRectangle(target1, target2, accurracy).width != 0;
		}
		
		/**
		 * 获取待检测两物体 包围盒 碰撞区域
		 * @param target1 待检测碰撞物体1
		 * @param target2 待检测碰撞物体2
		 * @return 返回 包围盒 碰撞区域
		 * 
		 */		
		public static function intersectionRectangle(target1:DisplayObject, target2:DisplayObject):Rectangle
		{
			// If either of the items don't have a reference to stage, then they are not in a display list
			// or if a simple hitTestObject is false, they cannot be intersecting.
			if(!target1.root || !target2.root || !target1.hitTestObject(target2)) return new Rectangle();
			
			// Get the bounds of each DisplayObject.
			var bounds1:Rectangle = target1.getBounds(target1.root);
			var bounds2:Rectangle = target2.getBounds(target2.root);
			
			// Determine test area boundaries.
			var intersection:Rectangle = new Rectangle();
			intersection.x = Math.max(bounds1.x, bounds2.x);
			intersection.y = Math.max(bounds1.y, bounds2.y);
			intersection.width = Math.min((bounds1.x + bounds1.width) - intersection.x, (bounds2.x + bounds2.width) - intersection.x);
			intersection.height = Math.min((bounds1.y + bounds1.height) - intersection.y, (bounds2.y + bounds2.height) - intersection.y);
			
			return intersection;
		}
		
		/**
		 * 获取待检测两物体 实际 碰撞区域
		 * @param target1 待检测碰撞物体1
		 * @param target2 待检测碰撞物体2
		 * @param accurracy
		 * @return 返回 实际 碰撞区域
		 * 
		 */		
		public static function complexIntersectionRectangle( target1:DisplayObject, target2:DisplayObject, accurracy:Number = 1 ):Rectangle
		{                  
			if (accurracy <= 0) throw new Error("ArgumentError: Error #5001: Invalid value for accurracy", 5001);
			
			// If a simple hitTestObject is false, they cannot be intersecting.
			if (!target1.hitTestObject(target2)) return new Rectangle();
			
			var hitRectangle:Rectangle = intersectionRectangle(target1, target2);
			// If their boundaries are no interesecting, they cannot be intersecting.
			if(hitRectangle.width * accurracy < 1 || hitRectangle.height * accurracy < 1) return new Rectangle();
			
			var bitmapData:BitmapData = new BitmapData(hitRectangle.width * accurracy, hitRectangle.height * accurracy, false, 0x000000);
			
			// Draw the first target.
			bitmapData.draw(target1, CollisionDetection.getDrawMatrix(target1, hitRectangle, accurracy), new ColorTransform(1, 1, 1, 1, 255, -255, -255, 255));
			// Overlay the second target.
			bitmapData.draw(target2, CollisionDetection.getDrawMatrix(target2, hitRectangle, accurracy), new ColorTransform(1, 1, 1, 1, 255, 255, 255, 255), BlendMode.DIFFERENCE);
			
			// Find the intersection.
			var intersection:Rectangle = bitmapData.getColorBoundsRect(0xFFFFFFFF, 0xFF00FFFF);
			
			bitmapData.dispose();
			
			// Alter width and positions to compensate for accurracy
			if (accurracy != 1)
			{
				intersection.x /= accurracy;
				intersection.y /= accurracy;
				intersection.width /= accurracy;
				intersection.height /= accurracy;
			}
			
			intersection.x += hitRectangle.x;
			intersection.y += hitRectangle.y;
			
			return intersection;
		}
		
		protected static function getDrawMatrix(target:DisplayObject, hitRectangle:Rectangle, accurracy:Number):Matrix
		{
			var localToGlobal:Point;
			var matrix:Matrix;
			
			var rootConcatenatedMatrix:Matrix = target.root.transform.concatenatedMatrix;
			
			localToGlobal = target.localToGlobal(new Point());
			matrix = target.transform.concatenatedMatrix;
			matrix.tx = localToGlobal.x - hitRectangle.x;
			matrix.ty = localToGlobal.y - hitRectangle.y;
			
			matrix.a = matrix.a / rootConcatenatedMatrix.a;
			matrix.d = matrix.d / rootConcatenatedMatrix.d;
			if(accurracy != 1) matrix.scale(accurracy, accurracy);
			
			return matrix;
		}
	}
}